package db

import (
	"database/sql"
	"io/ioutil"
	"encoding/json"
	"../env"
	"fmt"
)

var MysqlDb *sql.DB

var MysqlConfig = mysqlConfig{}
var configPathPreFix = "db/dbConfig-"
var configPathSuffix = ".json"

type mysqlConfig struct {
	User     string `json:"user"`
	Password string `json:"password"`
	Addr     string `json:"addr"`
	Port     string `json:"port"`
	DbName   string `json:"db_name"`
}

func init() {
	var err error
	//b, err := ioutil.ReadFile("./conf/db/dbConfig-dev.json")
	b, err := ioutil.ReadFile(env.EvnConfig.Cp+configPathPreFix + env.EvnConfig.Active + configPathSuffix)
	if err != nil {
		panic(err)
	}

	err = json.Unmarshal(b, &MysqlConfig)
	dataSourceName := MysqlConfig.User + ":" + MysqlConfig.Password + "@tcp(" + MysqlConfig.Addr + ":" + MysqlConfig.Port + ")/" + MysqlConfig.DbName
	fmt.Println("db:" , MysqlConfig)
	MysqlDb, err = sql.Open("mysql", dataSourceName)
	//MysqlDb,err  = sql.Open("mysql", "root:root@tcp(localhost:3306)/market")
	if err != nil {
		panic("数据库连接失败")
	}

	_, err = MysqlDb.Query("SELECT  1")

	if err != nil {
		panic("数据库不可用")
	}
}
